package org.itboys.core.service.mysql.web;

import com.alibaba.fastjson.JSONObject;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.core.common.ExceptionEnum;
import org.itboys.core.common.SundayCommonConstants;
import org.itboys.core.dao.order.SundayOrderSceneMapper;
import org.itboys.core.dto.order.SundayOrderDto;
import org.itboys.core.entity.mongo.SundayCart;
import org.itboys.core.entity.mongo.SundayCartGoodsSize;
import org.itboys.core.entity.mongo.SundayMember;
import org.itboys.core.entity.mysql.SundayOrder;
import org.itboys.core.entity.mysql.SundayOrderScene;
import org.itboys.core.service.mongo.front.SundayFrontCartGoodsSizeService;
import org.itboys.core.service.mongo.front.SundayFrontCartService;
import org.itboys.core.service.mongo.front.SundayFrontMemberService;
import org.itboys.core.util.JNBYRequestUtil;
import org.itboys.framework.query.JsonPageUtils;
import org.itboys.mysql.service.BaseMySqlService;
import org.itboys.param.PageResult;
import org.itboys.param.ParamUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 作者：zzq
 * 时间：2018/10/26
 * 描述：订单
 */
@Service
public class SundayOrderService extends BaseMySqlService<SundayOrder> {
    @Autowired
    private SundayOrderSceneMapper orderSceneMapper;
    @Autowired
    private SundayFrontMemberService memberService;
    @Autowired
    private SundayFrontCartService cartService;
    @Autowired
    private SundayFrontCartGoodsSizeService sizeService;
    /**
     * 分页查询
     *
     * @param request
     * @return
     */
    public PageResult<SundayOrder> select(HttpServletRequest request) throws IOException {
        Map<String, Object> param = ParamUtil.packageMysqlPageParam(request, "receiveName","orderNo","createTime_start","createTime_end");
        Integer orderStatus=Integer.valueOf(request.getParameter("orderStatus"));
        if (orderStatus != 0) {
            if (orderStatus == SundayCommonConstants.ORDER_STATUS_PSZ) {
                param.put("orderStatus", SundayCommonConstants.ORDER_STATUS_DPS);
            } else {
                param.put("orderStatus", orderStatus);
            }
        }
        List<SundayOrder> orders = super.select(param);
        List<SundayOrder> _orders = new ArrayList<>();
        List<String> orderNos = new ArrayList<>();
        if (ListUtil.isNotNull(orders)) {
            for (SundayOrder order : orders) {
                orderNos.add(order.getOrderNo());
            }
            JSONObject paramJson = new JSONObject();
            paramJson.put("orderNos", orderNos);
            paramJson.put("pageNo", 1);
            paramJson.put("pageSize", 20);
            JSONObject requestResult = JNBYRequestUtil.request(paramJson, "108d1f62b2e7f5a755230479f5eff13d", SundayCommonConstants.order_select_url);
            logger.info("江南布衣订单列表请求结果" + requestResult.toJSONString());
            List<JSONObject> jsonObjects = (List<JSONObject>) requestResult.get("data");
            if (ListUtil.isNotNull(jsonObjects)) {
                for (SundayOrder order : orders) {
                    for (JSONObject object : jsonObjects) {
                        Integer _orderStatus = (Integer) object.get("orderStatus");
                        if (object.get("orderNo").equals(order.getOrderNo()) ) {
                            if (order.getOrderStatus() == SundayCommonConstants.ORDER_STATUS_DPS&&_orderStatus == 2) {
                                order.setOrderStatus(SundayCommonConstants.ORDER_STATUS_PSZ);
                                break;
                            }
                            if(order.getOrderStatus() == SundayCommonConstants.ORDER_STATUS_TKZ&&_orderStatus == 4){
                                order.setOrderStatus(SundayCommonConstants.ORDER_STATUS_YTK);
                                break;
                            }
                        }
                    }
                    if (order.getOrderStatus() == SundayCommonConstants.ORDER_STATUS_PSZ) {
                        _orders.add(order);
                    }
                }
            }
        }
        if (orderStatus == SundayCommonConstants.ORDER_STATUS_PSZ) {
            return new PageResult<>(_orders, super.count(param));
        }
        return new PageResult<>(orders, super.count(param));
    }

    /**
     * 查询订单详情
     *
     * @param orderId
     * @return
     */
    public SundayOrderDto findOne(Long orderId) throws IOException {
        SundayOrderDto dto = packageSingleDto(super.find(orderId), null);
        JSONObject paramJson = new JSONObject();
        paramJson.put("orderNo", dto.getOrderNo());
        JSONObject object = JNBYRequestUtil.request(paramJson, "108d1f62b2e7f5a755230479f5eff13d", SundayCommonConstants.order_find_url);
        JSONObject data = (JSONObject) object.get("data");
        if(data!=null){
            Integer orderStatus = (Integer) data.get("orderStatus");
            if (orderStatus == 2) {
                dto.setOrderStatus(SundayCommonConstants.ORDER_STATUS_PSZ);
                dto.setSendCode((String) object.get("fastno"));
            }
            if (dto.getOrderStatus()==SundayCommonConstants.ORDER_STATUS_TKZ&&orderStatus == 4) {
                dto.setOrderStatus(SundayCommonConstants.ORDER_STATUS_YTK);
            }
            if (dto.getOrderStatus()==SundayCommonConstants.ORDER_STATUS_THZ&&orderStatus == 4) {
                dto.setOrderStatus(SundayCommonConstants.ORDER_STATUS_YTH);
            }
        }
        return dto;
    }

    /**
     * 再次向江南布衣发起订单
      * @param orderId
     */
    public void createOrder(Long orderId) throws IOException {
        SundayOrder order = super.find(orderId);
        if(order.getIsCreateOrder()!=SundayCommonConstants.NO){
            throw new ErrorException(ExceptionEnum.ORDER_STATUS_EXCEPTION.getValue());
        }
        Integer isCreateOrder=0;
        String createOrderMsg = "";
        Map<String, Object> param = new HashMap<String, Object>();
        SundayMember member = memberService.getById(order.getMemberId());
        param.clear();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("status", SundayCommonConstants.YES);
        param.put("orderId", order.getId());
        List<SundayCart> carts = cartService.list(param);
        List<Long> cartIds = carts.stream().map(e -> e.getId()).collect(Collectors.toList());
        param.clear();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("cartId in", cartIds);
        List<SundayCartGoodsSize> sizes = sizeService.list(param);
        if(ListUtil.isNotNull(sizes)){
            JSONObject paramJson = new JSONObject();
            paramJson.put("c_vip_id", member.getCUserId());
            paramJson.put("sourceCode", order.getOrderNo());
            paramJson.put("description", order.getDescription());
            paramJson.put("receiver_name",  order.getReceiveName());
            paramJson.put("c_province_id", String.valueOf(order.getProvinceId()));
            paramJson.put("c_city_id", String.valueOf(order.getCityId()));
            paramJson.put("c_district_id", String.valueOf(order.getDistrictId()));
            paramJson.put("receiver_address", order.getReceiveAddress());
            paramJson.put("receiver_mobile", order.getReceiveMobile());
            paramJson.put("source", "MART");
            paramJson.put("outcode", "104");
            List<JSONObject> productItem=new ArrayList<>();
            for (SundayCartGoodsSize size : sizes) {
                JSONObject codeSize=new JSONObject();
                codeSize.put("id", size.getGoodsId());
                codeSize.put("codeId", size.getCodeId());
                codeSize.put("qty", String.valueOf(size.getNum()));
                codeSize.put("priceactual", String.valueOf(size.getPrice()));
                productItem.add(codeSize);
            }
            paramJson.put("productItem", productItem);
            List<JSONObject> payitem=new ArrayList<>();
            JSONObject wxPay=new JSONObject();
            wxPay.put("c_payway_id", "62");
            wxPay.put("payamount", String.valueOf(order.getPayAmount()));
            payitem.add(wxPay);
            paramJson.put("payitem", payitem);
            logger.info("江南布衣创建订单参数 = {}", paramJson.toJSONString());
            JSONObject requestResult =JNBYRequestUtil.request(paramJson, "108d1f62b2e7f5a755230479f5eff13d", SundayCommonConstants.order_add_url);
            logger.info("江南布衣创建订单结果"+requestResult.toJSONString());
            if (requestResult.get("code").equals("0000")) {
                JSONObject data= (JSONObject) requestResult.get("data");
                Integer ret=data.getIntValue("ret");
                createOrderMsg=data.getString("msg");
                if(ret==1){
                    isCreateOrder=1;
                }
            }else {
                logger.info(ExceptionEnum.JNBY_CREATE_ORDER_EXCEPTION.getValue());
                //throw new ErrorException(ExceptionEnum.JNBY_CREATE_ORDER_EXCEPTION.getValue());
            }
            order.setCreateOrderMsg(createOrderMsg);
            order.setIsCreateOrder(isCreateOrder);
            super.update(order);
        }
    }

    /**
     * 组装DTO
     *
     * @param order
     * @return
     */
    public SundayOrderDto packageSingleDto(SundayOrder order, List<SundayOrderScene> scenes) {
        SundayOrderDto dto = new SundayOrderDto();
        if (ListUtil.isNull(scenes)) {
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("orderId", order.getId());
            scenes = new ArrayList<SundayOrderScene>();
            for (SundayOrderScene orderScene : orderSceneMapper.select(param)) {
                if (orderScene.getOrderId().longValue() == order.getId()) {
                    scenes.add(orderScene);
                }
            }
        }
        BeanUtils.copyProperties(order, dto);
        dto.setScenes(scenes);
        return dto;

    }


    /**
     * 分页获取订单商品
     * @param request
     * @param orderId
     * @return
     */
    public PageResult<SundayOrderScene> selectScene(HttpServletRequest request, Long orderId ){
        Map<String,Object> param = ParamUtil.packageMysqlPageParam(request,"");
        param.put("orderId",orderId);
        Serializable count = orderSceneMapper.count(param);
        Long countResult = count==null?0l: Long.valueOf(count.toString());
        return  new PageResult<SundayOrderScene>(orderSceneMapper.select(param),countResult);
    }

}
